import json
import argparse
import os

BLOG_ROOT = "./data/blog"
TOPIC_JSON_PATH = os.path.join(BLOG_ROOT, 'topic.count.json')
meta_path = os.path.join(BLOG_ROOT, "meta.json")


def count_meta_json(path: str) -> dict:
    with open(path, 'r', encoding='utf-8') as fp:
        obj = json.load(fp)
    counts = {}
    for blog_item in obj['blog']:
        topics = blog_item['topic']
        if isinstance(topics, list) and len(topics) > 0:
            for topic in topics:
                counts[topic] = counts.get(topic, 0) + 1
    
    return counts

def update_topic_json(max_hot_n=7):
    counts = count_meta_json(meta_path)
    max_hot_words = sorted(counts, key=lambda k: counts[k], reverse=True)
    max_hot_n_words = max_hot_words[:max_hot_n]
    obj = {
        'hot_topics': max_hot_n_words
    }
    with open(TOPIC_JSON_PATH, 'w', encoding='utf-8') as fp:
        json.dump(obj, fp, ensure_ascii=False, indent=4)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument('-n', type=int, help='最多的n个topic')
    args = parser.parse_args()
    update_topic_json(args.n)